package com.ycu.jk16.mall.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ycu.jk16.mall.domain.Order;
import com.ycu.jk16.mall.domain.OrderDetail;
import com.ycu.jk16.mall.domain.Product;
import com.ycu.jk16.mall.domain.Shipping;
import com.ycu.jk16.mall.domain.User;
import com.ycu.jk16.mall.service.OrderService;
import com.ycu.jk16.mall.util.assistdata.AssistOrder;
import com.ycu.jk16.mall.util.assistdata.AssistOrderItem;
import com.ycu.jk16.mall.util.assistdata.AssistShipping;
import com.ycu.jk16.mall.util.common.AndroidMalConstant;
import com.ycu.jk16.mall.util.common.PageUtil;
import com.ycu.jk16.mall.util.common.ResponseJsonUtils;

/**
 * 
 * @ClassName OrderController  
 * @Description TODO(这里用一句话描述这个类的作用) 
 * @author 倪宗龙
 * @date 2018年12月20日 下午11:35:37  
 * @version V1.0
 */
@Controller
@RequestMapping(value = "/order")
public class OrderController {
	@Autowired
	@Qualifier("orderService")
	private OrderService orderService;

	@RequestMapping(value = "/create")
	public void createOrder(@RequestParam("userId") Integer userId, @RequestParam("shippingId") Integer shippingId,
			@RequestParam("order") CommonsMultipartFile order, HttpServletResponse response)
			throws IllegalStateException, IOException {
		Map<String, Object> orderDataMap = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();

		try {
			// 保存订单文件
			String orderPath = savefile(order);

			Order orderData = new Order();
			OrderDetail orderDetail = new OrderDetail();
			AssistOrderItem assistOrderItem = new AssistOrderItem();
			List<AssistOrderItem> assistOrderItems = new ArrayList<>();
			List<OrderDetail> orderDeatils = new ArrayList<>();
			
			// 读取订单数据
			String orderJsonData = readJson(orderPath);
			JSONObject orderJson = JSON.parseObject(orderJsonData);
			BigDecimal payment = orderJson.getBigDecimal("totalPayment");
			orderData.setPayment(payment);
			
			Date createTime = orderJson.getDate("createTime");
			orderData.setCreateTime(createTime);
			orderData.setUser(new User(userId));
			orderData.setShipping(new Shipping(shippingId));
			
			JSONArray orderInfo = orderJson.getJSONArray("orderInfo");
			for (Object obj : orderInfo) {
				JSONObject info = (JSONObject) obj;
				
				// 设置订单编号
				orderData.setNo(orderData.getUser().getId() + String.valueOf(new Date().getTime()));
				assistOrderItem.setOrderNo(orderData.getNo());
				orderDetail.setOrder(orderData);
				
				orderDetail.setProduct(new Product(info.getInteger("id")));
				assistOrderItem.setProductId(orderDetail.getProduct().getId());
				assistOrderItem.setProductImage(new Product(assistOrderItem.getProductId()).getImageHost());
				
				orderDetail.setCurrentProductName(info.getString("name"));
				assistOrderItem.setProductName(orderDetail.getCurrentProductName());
				
				orderDetail.setCurrentUnitPrice(info.getBigDecimal("price"));
				assistOrderItem.setCurrentUnitPrice(orderDetail.getCurrentUnitPrice());
				
				orderDetail.setQuantity(info.getInteger("quantity"));
				assistOrderItem.setQuantity(orderDetail.getQuantity());
				
				assistOrderItems.add(assistOrderItem);
				orderDeatils.add(orderDetail);
			}

			orderService.addOrder(orderData, orderDeatils, userId);

			orderDataMap.put("status", 0);
			data.put("orderNo", orderData.getNo());
			data.put("payment", orderData.getPayment());
			data.put("paymentType", 1);
			data.put("postage", 0);
			data.put("status", 10);
			data.put("paymentTime", null);
			data.put("sendTime", null);
			data.put("endTime", null);
			data.put("closeTime", null);
			data.put("createTime", orderData.getCreateTime());
			data.put("orderItems", assistOrderItems);
			data.put("shippingId", shippingId);
			data.put("shippingVo", null);
			orderDataMap.put("data", data);
		} catch (NullPointerException e) {
			e.printStackTrace();
			orderDataMap.put("status", 1);
			orderDataMap.put("msg", "创建订单失败");
		} finally {
			ResponseJsonUtils.json(response, orderDataMap);
		}
	}

	/**
	 * 
	 * @Title getOrderCartProduct  
	 * @Description TODO(获取订单商品信息)  
	 * @param @param orderNo
	 * @param @param response
	 * @return void
	 * @throws
	 */
	@RequestMapping(value = "/get_order_cart_product")
	public void getOrderCartProduct(String orderNo, HttpServletResponse response) {
		Map<String, Object> orderProduct = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();

		try {
			// 测试catch块
			List<AssistOrderItem> assistOrderItems = new ArrayList<AssistOrderItem>();
			List<OrderDetail> detailList;
			// 加入json数据
			orderProduct.put("status", 0);
			detailList = orderService.findOrderDetailListByNo(orderNo);

			// orderItemVoList
			double totalPrice = 0.0;
			for (int j = 0; j < detailList.size(); j++) {
				OrderDetail orderDetail = detailList.get(j);
				AssistOrderItem assistOrderItem = new AssistOrderItem();
				assistOrderItem.setOrderNo(orderDetail.getOrder().getNo());
				assistOrderItem.setProductId(orderDetail.getProduct().getId());
				assistOrderItem.setSubTitle(orderDetail.getProduct().getSubtitle());
				assistOrderItem.setProductName(orderDetail.getCurrentProductName());
				assistOrderItem.setProductImage(orderDetail.getProduct().getMainImage());
				assistOrderItem.setCurrentUnitPrice(orderDetail.getCurrentUnitPrice());
				assistOrderItem.setQuantity(orderDetail.getQuantity());
				assistOrderItem.setTotalPrice(BigDecimal
						.valueOf(orderDetail.getQuantity() * orderDetail.getCurrentUnitPrice().doubleValue()));
				assistOrderItem.setCreateTime(orderDetail.getOrder().getCreateTime());
				// 添加订单详情，组成list
				assistOrderItems.add(assistOrderItem);
				totalPrice += assistOrderItem.getTotalPrice().doubleValue();
			}

			data.put("orderItems", assistOrderItems);
			data.put("imageHost", AndroidMalConstant.HOST_ADDRESS);
			data.put("productTotalPrice", totalPrice);
			orderProduct.put("data", data);
		} catch (NullPointerException e) {
			e.printStackTrace();
			orderProduct.put("status", 1);
			orderProduct.put("msg", "没登录");
		} finally {
			ResponseJsonUtils.json(response, orderProduct);
		}
	}

	/**
	 * 
	 * @Title getOrderList  
	 * @Description TODO(获取订单列表)  
	 * @param @param pageNum
	 * @param @param pageSize
	 * @param @param userId
	 * @param @param response
	 * @return void
	 * @throws
	 */
	@RequestMapping(value = "/list")
	public void getOrderList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
			@RequestParam(value = "pageSize", defaultValue = "10") int pageSize, Integer userId,
			HttpServletResponse response) {
		Map<String, Object> OrderListData = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> params = new HashMap<String, Object>();

		// 添加params参数
		params.put("pageNum", pageNum);
		params.put("pageSize", pageSize);
		params.put("userId", userId);

		// order的集合
		List<Order> orderList;
		List<OrderDetail> orderDetailList;
		List<AssistOrder> assistOrders = new ArrayList<>();
		

		try {
			// 测试catch块
			orderList = orderService.getOrdersWithParams(params);
			// page分页
			PageUtil page = new PageUtil(pageNum, pageSize, orderList.size());

			// 加入json数据
			OrderListData.put("status", 0);

			data.put("pageNum", pageNum);
			data.put("pageSize", pageSize);
			data.put("size", orderList.size());
			data.put("total", page.getRecordCount());
			data.put("pages", page.getTotalPage());
			// list
			for (int i = 0; i < orderList.size(); i++) {
				List<AssistOrderItem> assistOrderItems = new ArrayList<AssistOrderItem>();
				orderDetailList = orderService.findOrderDetailListByNo(orderList.get(i).getNo());
				// orderItemVoList
				for (int j = 0; j < orderDetailList.size(); j++) {
					OrderDetail orderDetail = orderDetailList.get(j);
					System.out.println("orderDetail="+orderDetail.getCurrentProductName());
					AssistOrderItem assistOrderItem = new AssistOrderItem();
					assistOrderItem.setOrderNo(orderDetail.getOrder().getNo());
					assistOrderItem.setProductId(orderDetail.getProduct().getId());
					assistOrderItem.setSubTitle(orderDetail.getProduct().getSubtitle());
					assistOrderItem.setProductName(orderDetail.getCurrentProductName());
					assistOrderItem.setProductImage(orderDetail.getProduct().getMainImage());
					assistOrderItem.setCurrentUnitPrice(orderDetail.getCurrentUnitPrice());
					assistOrderItem.setQuantity(orderDetail.getQuantity());
					assistOrderItem.setTotalPrice(BigDecimal
							.valueOf(orderDetail.getQuantity() * orderDetail.getCurrentUnitPrice().doubleValue()));
					assistOrderItem.setCreateTime(orderDetail.getOrder().getCreateTime());
					// 添加订单详情，组成list
					assistOrderItems.add(assistOrderItem);
				}

				Order order = orderList.get(i);
				AssistOrder assistOrder = new AssistOrder();
				assistOrder.setOrderNo(order.getNo());
				assistOrder.setPayment(order.getPayment());
				assistOrder.setPaymentTime(order.getCreateTime());
				assistOrder.setSendTime(order.getCreateTime());
				assistOrder.setEndTime(order.getEndTime());
				assistOrder.setCloseTime(order.getCloseTime());
				assistOrder.setCreateTime(order.getCreateTime());
				assistOrder.setImageHost(AndroidMalConstant.HOST_ADDRESS);
				assistOrder.setShippingId(order.getShipping().getId());
				assistOrder.setReceiverName(order.getShipping().getName());
				assistOrder.setOrderItems(assistOrderItems);
System.out.println("assistOrderItems="+assistOrderItems);

				// 添加assistOrder
				assistOrders.add(assistOrder);

			}
			data.put("list", assistOrders);
			OrderListData.put("data", data);
			OrderListData.put("firstPage", 1);
			OrderListData.put("prePage", page.hasPreviousPage(pageNum) ? pageNum - 1 : pageNum);
			OrderListData.put("nextPage", page.hasNextPage(pageNum) ? pageNum + 1 : pageNum);
			OrderListData.put("lastPage", page.getTotalPage());
			OrderListData.put("isFisrtPage", page.isFirstPage(pageNum));
			OrderListData.put("isLastPage", page.isLastPage(pageNum));
			OrderListData.put("hasPreviousPage", page.hasPreviousPage(pageNum));
			OrderListData.put("hasNextPage", page.hasNextPage(pageNum));
		} catch (NullPointerException e) {
			e.printStackTrace();
			OrderListData.put("status", 1);
			OrderListData.put("msg", "没登录");
		} finally {
			ResponseJsonUtils.json(response, OrderListData);
		}
	}

	/**
	 * 
	 * @Title detail  
	 * @Description TODO(订单详情)  
	 * @param @param orderNo
	 * @param @param response
	 * @return void
	 * @throws
	 */
	@RequestMapping(value = "/detail")
	public void detail(String orderNo, HttpServletResponse response) {
		Map<String, Object> orderListData = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> params = new HashMap<String, Object>();

		// 添加params参数
		int pageNum = 1, pageSize = 100;
		params.put("pageNum", pageNum);
		params.put("pageSize", pageSize);

		// order的集合
		List<OrderDetail> orderDetailList;
		List<AssistOrderItem> assistOrderItems = new ArrayList<AssistOrderItem>();

		try {
			// 测试catch块

			// 加入json数据
			orderListData.put("status", 0);

			// list
			orderDetailList = orderService.findOrderDetailListByNo(orderNo);
			// orderItemVoList
			for (int j = 0; j < orderDetailList.size(); j++) {
				OrderDetail orderDetail = orderDetailList.get(j);
				AssistOrderItem assistOrderItem = new AssistOrderItem();
				assistOrderItem.setOrderNo(orderDetail.getOrder().getNo());
				assistOrderItem.setProductId(orderDetail.getProduct().getId());
				assistOrderItem.setSubTitle(orderDetail.getProduct().getSubtitle());
				assistOrderItem.setProductName(orderDetail.getCurrentProductName());
				assistOrderItem.setProductImage(orderDetail.getProduct().getMainImage());
				assistOrderItem.setCurrentUnitPrice(orderDetail.getCurrentUnitPrice());
				assistOrderItem.setQuantity(orderDetail.getQuantity());
				assistOrderItem.setTotalPrice(BigDecimal
						.valueOf(orderDetail.getQuantity() * orderDetail.getCurrentUnitPrice().doubleValue()));
				assistOrderItem.setCreateTime(orderDetail.getOrder().getCreateTime());
				// 添加订单详情，组成list
				assistOrderItems.add(assistOrderItem);
			}

			Order order = orderService.findOrderByNo(orderNo);
			AssistOrder assistOrder = new AssistOrder();
			assistOrder.setOrderNo(order.getNo());
			assistOrder.setPayment(order.getPayment());
			assistOrder.setPaymentTime(order.getCreateTime());
			assistOrder.setSendTime(order.getCreateTime());
			assistOrder.setEndTime(order.getEndTime());
			assistOrder.setCloseTime(order.getCloseTime());
			assistOrder.setCreateTime(order.getCreateTime());
			assistOrder.setImageHost(AndroidMalConstant.HOST_ADDRESS);
			assistOrder.setShippingId(order.getShipping().getId());

			// Shipping
			Shipping shipping = order.getShipping();
			AssistShipping assistShipping = new AssistShipping();
			assistShipping.setReceiverAddress(shipping.getAddress());
			assistShipping.setReceiverCity(shipping.getCity());
			assistShipping.setReceiverPhone(shipping.getPhone());
			assistShipping.setReceiverMobile(shipping.getMobile());
			assistShipping.setReceiverProvince(shipping.getProvince());
			assistShipping.setReceiverZip(shipping.getZip());
			// 添加ShippingVo
			assistOrder.setShippingVo(assistShipping);

			assistOrder.setReceiverName(order.getShipping().getName());
			assistOrder.setOrderItems(assistOrderItems);

			data.put("order", assistOrder);
			orderListData.put("data", data);
		} catch (NullPointerException e) {
			e.printStackTrace();
			orderListData.put("status", 1);
			orderListData.put("msg", "没登录");
		} finally {
			ResponseJsonUtils.json(response, orderListData);
		}
	}

	String savefile(CommonsMultipartFile file) throws IllegalStateException, IOException {
		String path = file.getOriginalFilename();
		String dir = getClass().getResource("/").getPath();
		dir = dir.substring(0, dir.indexOf("WEB-INF"));
		File newFile = new File(dir + "upload/order" + path);
		if (!newFile.exists()) {
			newFile.mkdirs();
		}
		file.transferTo(newFile);
		return dir + "upload/order/" + path;
	}

	String readJson(String path) {
		String jsonString = "";
		File file = new File(path);
		Reader reader = null;
		try {
			System.out.println("以字符为单位读取文件内容，一次读一个字节：");
			// 一次读一个字符
			reader = new InputStreamReader(new FileInputStream(file));
			int tempchar;
			while ((tempchar = reader.read()) != -1) {
				// 对于windows下，\r\n这两个字符在一起时，表示一个换行。
				// 但如果这两个字符分开显示时，会换两次行。
				// 因此，屏蔽掉\r，或者屏蔽\n。否则，将会多出很多空行。
				if (((char) tempchar) != '\r') {
					System.out.print((char) tempchar);
					jsonString += (char) tempchar;
				}
			}
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return jsonString;
	}
}
